<?php

namespace app\health\model;

use RedisException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;

class HealthFuluOrder extends Model
{
    protected $type = [
        'type'         => 'integer',
        'order_status' => 'integer',
        'pay_status'   => 'integer',
    ];

    public function getOrderStatusTxtAttr($val, $data): string
    {
        if ($data['pay_status'] === 0) {
            return '未支付';
        }
        return $data['order_status'] === 0 ? '未完成' : '已完成';
    }

    /**
     * 关联订单商品信息
     * @return HasMany
     */
    public function orderItem(): HasMany
    {
        return $this->hasMany(HealthFuluOrderItem::class, 'order_id');
    }

    /**
     * 关联用户
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(HealthUser::class, 'user_id');
    }

    /**
     * @param $orderNo
     * @return array|bool|\PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws RedisException
     */
    public static function paySuccess($orderNo)
    {
        $orderInfo = self::where('order_no', $orderNo)->find();
        if ($orderInfo && $orderInfo['pay_status'] === 0) {
            $orderInfo->pay_status = 1;
            $orderInfo->pay_time   = time();
            $orderInfo->updated_at = date('Y-m-d H:i:s');
            $orderInfo->save();
            //支付成功发起充值服务
            queue_custom('app\common\job\FuluOrderRechargeJob', ['order_id' => $orderInfo['id']]);
            if ($orderInfo['type'] === 0) {
                //首次购买
                queue_custom('app\common\job\WebsiteTaskJob', [
                    'user_id'      => $orderInfo['user_id'],
                    'complete_way' => 4
                ], 0);
            }
        }
        return $orderInfo;
    }
}